1. Flashcards
What is scope in JS?
Scope determines the accessibility (visibility) of variables. In JavaScript there are two types of scope: Local scope, Global scope. Variables defined inside a function are not accessible (visible) from outside the function. Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
What is the Difference Between Scope and Context in JavaScript?
Scope pertains to the visibility of variables, and context refers to the object to which a function belongs.
The value of ‘this’ depends on where it is being invoked. Invoking ‘this’ in the global space will return the entire window object. because the window object is the starting point of all the code we write. If we invoke this in the context of a new object, it will return that object, ‘this’ will refer to that object.
What is “this”? (context)
Context tells us where we are within the object.
“this” refers to the object that the function is a property of. The value of “this” will always depend on the object that is invoking the function.
function doSomething() { console.log(this); } doSomething();
Since the function is invoked in the global context, the function is a property of the global object.
var obj = { name: "vivek", getName: function(){ console.log(this.name); } } obj.getName();
In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, the this keyword will refer to the object obj , and hence the output will be “vivek”.
var obj = { name: "vivek", getName: function(){ console.log(this.name); } } var getName = obj.getName;
var obj2 = {name:"akshay", getName }; obj2.getName();
The output will be “akshay”. Although the getName function is declared inside the object obj , at the time of invocation, getName() is a property of obj2 , therefore the “this” keyword will refer to obj2 .
var obj1 = { address : "Mumbai,India", getAddress: function(){ console.log(this.address); } } var getAddress = obj1.getAddress; var obj2 = {name:"akshay"}; obj2.getAddress();
The output will be an error. Although in the code above, the this keyword refers to the object obj2 , obj2 does not have the property “address”‘, hence the getAddress function throws an error.
What are JavaScript Data Types?
Following are the JavaScript Data types:
Number String Boolean Object Undefined
What is the use of isNaN function?
isNan function returns true if the argument is not a number; otherwise, it is false.
What is negative Infinity?
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.
Which company developed JavaScript?
Netscape is the software company that developed JavaScript.
What are undeclared and undefined variables?
Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.
Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.
Write the code for adding new elements dynamically?
t1
function addNode () { var newP = document. createElement("p"); var textNode = document.createTextNode(" This is a new text node"); newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); }
<p>firstP</p>
<p>
</p>
What are global variables? How are these variable declared?
Global variables are available throughout the length of the code so that it has no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.
Example:
// Declare a global: globalVariable = “Test”;
The problems faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.
What is ‘this’ keyword in JavaScript?
‘This’ keyword refers to the object from where it was called.
What is === operator?
=== is called a strict equality operator, which returns true when the two operands have the same value without conversion.
Does JavaScript support automatic type conversion?
Yes, JavaScript does support automatic type conversion.
How can the style/class of an element be changed?
document.getElementById(“myText”). style. fontSize = “20”;
or
document. getElementById (“myText”). className = “anyclass”;
What is a Closure?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
(To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function.)
The inner function will have access to the variables in the outer function scope, even after the outer function has returned.
const test = function (counterName) { let counter = 0; return function () { console.log(counterName, ++counter); } }
const counterA = test('Counter A') const counterB = test('Counter B')
counterA();
counterA();
counterA();
counterB();
What is a callback function? (EdX)
Callback is a function passed into another function as an argument to be executed later.
Why does Function Expression have a semicolon “;” at the end, but Function Declaration does not?
function sayHi() { // ... }
let sayHi = function() { // ... };
The answer is simple:
- There’s no need for ; at the end of code blocks and syntax structures that use them like if { … }, for { }, function f { } etc.
- A Function Expression is used inside the statement: let sayHi = …;, as a value. It’s not a code block, but rather an assignment. The semicolon ; is recommended at the end of statements, no matter what the value is.
So the semicolon here is not related to the Function Expression itself, it just terminates the statement.
What is Function expression?
This is when we create a function and assign it to the variable, like any other value. No matter how the function is defined, it’s just a value stored in the variable. Note: the semicolon “;” is recommended at the end of statements, since we assign the function to the variable (it is not a code block).
let sayHi = function() { alert( "Hello" ); };
The function above is actually an anonymous function (a function without a name). Arrow functions provide syntactic sugar for Function Expressions.
let sayHi = () => { alert( "Hello" ); };
Unlike function declarations, function expressions are NOT hoisted. These functions are only available when the JavaScript interpreter processes that line of code.
What is Function declaration?
Function Declarations begin with the function keyword, followed by the name of the function and any arguments it may take.
function showMessage() { alert( 'Hello everyone!' ); }
When defining a function using function declarations, the function is hoisted. A hoisted function or variable is placed at the top of their functional scope when JavaScript is executing code.
Note: Functional Scope refers to where a function was defined. For example, if a function foo() contained a function bar() inside of it, we would say that the functional scope of bar() is foo(). If foo() was not defined within a function, then foo() belongs to the global scope. JavaScript functions in the global scope are accessible to all the code that runs with it.
What is Immediately-Invoked Function Expressions (IIFE)?
IIFEs are functions that are executed immediately after being defined. The parentheses surrounding the function definition lets JavaScript know that it will process a function expression. The last pair of parentheses invoke the function.
(function() { // Code that runs in your function })()
(function(arg1, arg2) { // Code that runs in your function })("hello", "world");
When to Use an IIFE?
The most common use cases for IIFEs are:
- Adjustment global variables,
- Creating private variables or functions,
- Asynchronous functions in loops
- Aliasing Global Variables
If you have 2 libraries that export an object with the same name, you can use IIFEs to ensure they don’t conflict in your code. For example, the jQuery and Cash JavaScript libraries both export $ as their main object. Let’s say, we want to ensure that $ refers to the jQuery object, and not the cash alternative:
(function($) { // Code that runs in your function })(jQuery);
- Creating Private Variables and Functions
We can use IIFEs to create private variables and functions within the global scope, or any other function scope. Functions and variables added to the global scope are available to ALL scripts that are loaded on a page. If we load other JavaScript files in our browser, they also gain access to our function and variable. To prevent them from using or editing them, we encase (wrap/pack) our code in an IIFE:
(function () { function generateMagicNumber() { return Math.floor(Math.random() * 100) + 900; }
console.log("This is your magic number: " + generateMagicNumber());
var favoriteNumber = 5; console.log("Twice your favorite number is " + favoriteNumber * 2); })();
It runs the same, but now generateMagicNumber() and favoriteNumber are only accessible in our script.
- Asynchronous Functions in Loops.
When JavaScript meets asynchronous code, JS postpones execution of the callback function until the asynchronous task will be completed. In this example, the console.log() statement will run only after the timeout has expired/done.
for (var i = 1; i <= 5; i++) { setTimeout(function () { console.log('I reached step ' + i); }, 1000 * i); }
I reached step 6 I reached step 6 I reached step 6 I reached step 6 I reached step 6
This problem can be solved with an IIFE:
for (var i = 1; i <= 5; i++) { (function (step) { setTimeout(function() { console.log('I reached step ' + step); }, 1000 * i); })(i); }
By using an IIFE, we create a new scope for our callback function. Our IIFE takes a parameter step. Every time our IIFE is called, we give it the current value of i as its argument. Now, when the callback is ready to be executed, its closure will have the correct value of step.
I reached step 1 I reached step 2 I reached step 3 I reached step 4 I reached step 5
https://stackabuse.com/javascripts-immediately-invoked-function-expressions/
What typeof returns for a null value?
It returns “object”.