Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output 0 here. var a = 7; a.constructor();

Tags:

Let's look at the examples below:

Q1: Why is the output 0 here? What does it mean?

var a = 7;
console.log(a.constructor()); // prints 0 (Why?)

Q2: When typeof a and typeof 7 both are number, why a.constructor() runs whereas 7.constructor() doesn't?

var a = 7; 
var bool = typeof a === typeof 7;

console.log(a.constructor()); // 0
console.log((++a).constructor()); // 0

console.log(7.constructor()); // SyntaxError: Invalid or unexpected token
console.log(++a.constructor()); // ReferenceError: Invalid left-hand side expression in prefix operation
like image 443
Aaditya Sharma Avatar asked May 13 '19 13:05

Aaditya Sharma


1 Answers

Q1: Why is the output 0 here? What does it mean?

a.constructor is Number and you are calling it with first argument undefined. Because Number() returns undefined so x.constructor() returns undefined. If no argument is passed to Number() it returns 0

var a = 5;
console.log(a.constructor === Number)
console.log(Number())

When typeof a and typeof 7 both are number, why a.constructor() runs whereas 7.constructor() doesn't?

Actually 7. is itself a number. Here . doesnot work as Dot Notation but as decimal point because the digits after decimal point are optional.

Solution:

There can be different ways to directly access the method of number.

console.log(5..constructor)
console.log((5).constructor)
console.log(5 .constructor)
like image 147
Maheer Ali Avatar answered Nov 11 '22 07:11

Maheer Ali