-
JavaScript is a lightweight, interpreted programming language with object-oriented capabilities, that used for both on the client-side and server-side that allows you to make web pages interactive.
JavaScript is a case sensitive language. The language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
-
The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
• Global Scope − A global variable has global scope which means it is visible everywhere in your JavaScript code.
Example:windowobject has global scope it's accessible everywhere.• Local Scope (Block Scope) − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
Example: when variable declear withletorconstkey word in JavaScript. it will accessible within block.let a = 'Hello'; // global variable function greet() { let b = 'World'; // local variable console.log(a + ' ' + b); if (b == 'World') { let c = 'hello'; // block-scoped variable console.log(a + ' ' + b + ' ' + c); } console.log(a + ' ' + b + ' ' + c); // variable c cannot be accessed here } greet();
-
In JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error
var name is not definedand the script will stop executing thereafter. But If you usetypeof undeclared_variablethen it will returnundefined.Before starting further discussion let's understand the difference between declaration and definition.
var xis a declaration because we are not defining what value it holds yet, but we are declaring its existence and the need for memory allocation.var x; // declaring x console.log(x); // output: undefined
var x = 1is both declaration and definition, here declaration and assignment of value happen inline for variable x—what we are doing is called "initialisation". In JavaScript both variable declarations and function declarations go to the top of the scope in which they are declared, then assignment happens—this series of events is called "hoisting".A variable can be declared but not defined. When we try to access it, It will result
undefined.var x; // Declaration typeof x === 'undefined'; // Will return true
A variable can be neither declared nor defined. When we try to reference such variable then the result will be
not defined.console.log(y); // Output: ReferenceError: y is not defined
-
A closure is a function defined inside another function (called parent function) and as such it has access to the variables declared and defined within its parent function's scope.
The closure has access to the variables in three scopes:
- Variable declared in its own scope
- Variable declared in its parent function's scope
- Variable declared in the global namespace
var globalVar = "abc"; //Global variable // Parent self-invoking function (function outerFunction (outerArg) { // start of outerFunction's scope var outerFuncVar = 'x'; // Variable declared in outerFunction's function scope // Closure self-invoking function (function innerFunction (innerArg) { // start of innerFunction's scope var innerFuncVar = "y"; // variable declared in innerFunction's function scope console.log( "outerArg = " + outerArg + "\n" + "outerFuncVar = " + outerFuncVar + "\n" + "innerArg = " + innerArg + "\n" + "innerFuncVar = " + innerFuncVar + "\n" + "globalVar = " + globalVar); // end of innerFunction's scope })(5); // Pass 5 as parameter to our Closure // end of outerFunction's scope })(7); // Pass 7 as parameter to the Parent function
innerFunctionis a closure which is defined insideouterFunctionand consequently has access to all the variables which have been declared and defined withinouterFunction's scope as well as any variables residing in the program's global scope.The output of the code above would be:
outerArg = 7 outerFuncVar = x innerArg = 5 innerFuncVar = y globalVar = abc
-
JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value.
There are two special cases in this,
- NaN is not equal to anything, including NaN.
- Positive and negative zeros are equal to one another.
- Two Boolean operands are strictly equal if both are true or both are false.
- Two objects are strictly equal if they refer to the same Object.
- Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined --> false but null==undefined --> true
Some of the example which covers the above cases,
0 == false // true 0 === false // false 1 == "1" // true 1 === "1" // false null == undefined // true null === undefined // false '0' == false // true '0' === false // false []==[] or []===[] //false, refer different objects in memory {}=={} or {}==={} //false, refer different objects in memory
========================================================================================================================================================================================================================
-
getMessage(); var getMessage = () => { console.log("Good morning"); };
- 1: Good morning
- 2: getMessage is not a function
- 3: getMessage is not defined
- 4: Undefined
Answer
Hoisting will move variables and functions to be the top of scope. Even though getMessage is an arrow function the above function will considered as a varible due to it's variable declaration or assignment. (Like all other functions in Javascript, the arrow function is not hoisting the main reason that you cannot call them before initialization.) So the variables will have undefined value in memory phase and throws an error '
getMessageis not a function' at the code execution phase.
-
if( x <= 100 ) {...} if( !(x > 100) ) {...}
Answer
NaN <= 100isfalseandNaN > 100is alsofalse, so if the value ofxisNaN, the statements are not the same.The same holds true for any value of x that being converted to type Number, returns
NaN, e.g.:undefined,[1,2,5],{a:22}, etc.This is why you need to pay attention when you deal with numeric variables.
NaNcan’t be equal, less than or more than any other numeric value, so the only reliable way to check if the value isNaN, is to use theisNaN()function.
-
var x = 1; var output = (function() { delete x; return x; })(); console.log(output);
Answer
The code above will output `1` as output. `delete` operator is used to delete a property from an object. Here `x` is not an object it's **global variable** of type `number`.
-
var Employee = { company: 'xyz' } var empOne = Object.create(Employee); delete empOne.company console.log(empOne.company);
Answer
The code above will output `xyz` as output. Here `emp1` object got company as **prototype** property. delete operator doesn't delete prototype property.
emp1object doesn't have company as its own property. you can test itconsole.log(emp1.hasOwnProperty('company')); //output : falseHowever, we can delete company property directly fromEmployeeobject usingdelete Employee.companyor we can also delete fromemp1object using__proto__propertydelete emp1.__proto__.company.
var z = 1, y = z = typeof y;
console.log(y);Answer
The code above will print string `"undefined"` as output. According to associativity rule operator with the same precedence are processed based on their associativity property of operator. Here associativity of the assignment operator is `Right to Left` so first `typeof y` will evaluate first which is string `"undefined"` and assigned to `z` and then `y` would be assigned the value of z. The overall sequence will look like that:
var z;
z = 1;
var y;
z = typeof y;
y = z;console.log(add(5)(4)(6)); // output : 15
console.log(add(8)(3)(9)); // output : 20Details
function add (x) {
return function (y) { // anonymous function
return function (z) { // anonymous function
return x + y + z;
};
};
}Here the add function accepts the first argument and returns an anonymous function which then takes the second parameter and returns one last anonymous function which finally takes the third and final parameter; the last function then sum x, y and z, and returns the result of the operation.
In Javascript, a function defined inside another function has access to the outer function's scope and can consequently return, interact with or pass on to other functions, the variables belonging to the scopes that incapsulate it.
- A function is an instance of the Object type
- A function can have properties and has a link to its constructor method
- A function can be stored as a variable
- A function can be passed as a parameter to another function
- A function can be returned by another function
let c = { greeting: 'Hey!' };
let d;
d = c;
c.greeting = 'Hello';
console.log(d.greeting);- A:
Hello - B:
Hey! - C:
undefined - D:
ReferenceError - E:
TypeError
Answer
In JavaScript, all objects interact by reference when setting them equal to each other.
First, variable c holds a value to an object. Later, we assign d with the same reference that c has to the object.
When you change one object, you change all of them.
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);- A:
truefalsetrue - B:
falsefalsetrue - C:
truefalsefalse - D:
falsetruetrue
Answer
new Number() is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object.
When we use the == operator (Equality operator), it only checks whether it has the same value. They both have the value of 3, so it returns true.
However, when we use the === operator (Strict equality operator), both value and type should be the same. It's not: new Number() is not a number, it's an object. Both return false.