One of the crucial features introduced in ECMAScript 5 (ES5) is Strict Mode. In this blog, we will delve into what Strict Mode is, why it is important, and how it affects the declaration and behavior of variables in JavaScript.
What is Strict Mode?
in JavaScript, Strict Mode is a feature introduced in ECMAScript 5 that enables you to run a program or function in a “strict” operating context. It helps identify common coding errors, prevents the use of potentially problematic syntax, and generally makes your code more robust and secure.
How to implement/enable strict mode?
To enable Strict Mode, you simply add the string "use strict";
at the beginning of your script or function. For example:
"use strict";
function myFunction() {
// Your code here
}
Can we enable Strict Mode for a Single Function?
Yes, you can enable strict mode for a single function by placing the "use strict";
directive at the beginning of the function body. Here is an example:
function myFunction() {
"use strict";
// Your code here
}
To know more about functions, click here.
What are the benefits of Strict Mode?
Strict mode makes it easier to write “secure” JavaScript.
Variables must be declared before use: In Strict Mode, undeclared variables will throw an error. It helps to avoid the accidental creation of global variables.
"use strict";
myVar = 10; // Error: myVar is not defined
Assignment to non-writable properties: In Strict Mode, assigning values to non-writable properties will throw an error.
"use strict";
Object.defineProperty(window, "myVar", { value: 42, writable: false });
myVar = 9; // Error: Cannot assign to read-only property 'myVar'
‘this’ keyword behavior: In Strict Mode, this
remains undefined
in functions that are called as plain functions (not as object methods).
"use strict";
function testThis() {
console.log(this); // undefined
}
testThis();
Use of eval: Using eval in strict mode has some important differences compared to using it in non-strict mode.
In strict mode, eval
does not create or modify variables in the containing scope. It creates its own scope.
"use strict";
function testEval() {
eval("var y = 3;console.log(y);");
}
testEval();
// output: 3
Variables declared inside eval
remain within the eval
scope and are not accessible outside.
"use strict";
function testEval() {
eval("var y = 3;");
console.log(y);
}
testEval();
// output:
ReferenceError: y is not defined
Reserved keywords as variable names in Strict Mode are not allowed: Using reserved keywords as variable names will throw a SyntaxError
in Strict Mode. For example:
"use strict";
var private = "secret"; // SyntaxError: Unexpected strict mode reserved word
Variables
What is Variables?
In JavaScript, a variable is a named container that holds a value that can be changed during the execution of a program.
Basics of JavaScript Variables
- What are the different ways to declare a variable in JavaScript?
var
,let
, andconst
.
- Does variable case matter in JavaScript?
- Yes, variable case does matter in JavaScript. The two variables with different casing are considered to be different variables. var myname and var myName are different variables.
- Can you explain the concept of variable hoisting in JavaScript?
- Variable declarations using
var
are hoisted to the top of their scope, meaning they can be referenced before they are declared. However, their initialization is not hoisted. Variables declared withlet
andconst
are also hoisted but are not initialized, leading to a “temporal dead zone.”
- Variable declarations using
- What is the scope of a variable declared with
var
?- Function scope.
- What is the scope of a variable declared with
let
andconst
?- Block scope.
- How does block scope differ from function scope in JavaScript?
- Block scope confines variables to the nearest enclosing
{}
block, while function scope confines variables to the function they are declared in.
- Block scope confines variables to the nearest enclosing
- What will happen if you try to reassign a
const
variable?- It will throw a TypeError.
- Can you declare a variable without initializing it? What will be its value?
- Yes, it will be
undefined
.
- Yes, it will be
Advanced Concepts
- Explain the concept of temporal dead zone (TDZ) in JavaScript.
- The TDZ is the time between entering a scope and the actual declaration of a variable with
let
orconst
. During this period, accessing the variable results in a ReferenceError.
- The TDZ is the time between entering a scope and the actual declaration of a variable with
- How do
var
,let
, andconst
variables behave inside loops?var
variables are function-scoped and can lead to unexpected results inside loops due to hoisting.let
andconst
are block-scoped and thus confined to the loop block, avoiding such issues.
- What are global variables, and how can you create them in JavaScript?
- Global variables are accessible throughout the entire script. They can be created by declaring a variable outside any function or by omitting the
var
,let
, orconst
keyword (not recommended).
- Global variables are accessible throughout the entire script. They can be created by declaring a variable outside any function or by omitting the
- What is the purpose of the
global
object in JavaScript, and how do variables interact with it?- The
global
object (likewindow
in browsers andglobal
in Node.js) is the top-level object that contains all global variables and functions. Global variables declared withvar
become properties of this object.
- The
- Can you explain shadowing in the context of variable declarations?
- Shadowing occurs when a variable declared in a local scope has the same name as a variable declared in an outer scope. The inner variable shadows the outer one within its scope.
- What is the precedence order between local and global variables?
- In JavaScript, the precedence order between local and global variables is determined by the scope in which they are declared. Local variables take precedence over global variables when they share the same name. This means that if a local variable is declared with the same name as a global variable, the local variable will shadow the global variable within its scope.
- Local variables have higher precedence than global variables with the same name within their scope.
- How does variable declaration inside a function differ from variable declaration in the global scope?
- Variables declared inside a function are local to that function and cannot be accessed outside of it, whereas global variables are accessible throughout the entire script.
- What are immediately invoked function expressions (IIFE), and how do they affect variable scope?
- IIFEs are functions that are executed immediately after they are defined. They create a new scope, which can be used to avoid polluting the global scope with temporary variables.
Specific Use Cases
- What happens if you declare a variable multiple times using
var
?- Only the first declaration will be hoisted, and subsequent declarations will overwrite the variable’s value.
- How do you ensure a variable is not reassignable after its initial assignment?
- Declare it using
const
.
- Declare it using
- Can you explain how closures work in JavaScript and their relationship with variable scope?
- A closure is a function that retains access to its lexical scope even when executed outside that scope. It allows the function to remember the environment in which it was created.
- What are the implications of using
var
in a loop with asynchronous callbacks?- Using
var
can lead to unexpected behavior because it is function-scoped, and all loop iterations share the same variable. This can result in all callbacks referencing the same variable value.
- Using
- Why is it generally recommended to use
let
andconst
overvar
?let
andconst
provide block scope, reducing the likelihood of bugs caused by variable hoisting and unintentional overwriting.
Best Practices and Common Pitfalls
- What are some best practices for naming variables in JavaScript?
- To improve code clarity, Use meaningful and descriptive names.
- For variables and functions, apply camelCase formatting.
- Use uppercase letters for constants.
- Avoid using reserved words or global variable names.
- Why is it important to avoid global variables, and how can you minimize their use?
- Global variables can lead to name collisions and unintended side effects. Minimize their use by encapsulating code in functions, modules, or using block-scoped variables.
- Can you give an example of a situation where using
const
is preferable tolet
?- Use
const
when the variable should not be reassigned, such as when defining configuration settings or fixed values.
- Use
- What is the difference between declaring a variable at the top of a function versus within a block inside the function?
- Declaring a variable at the top of a function makes it accessible throughout the function. Declaring it within a block confines it to that block, preventing it from being accessed outside.
- What issues can arise from forgetting to use
let
orconst
when declaring a variable?- The variable will become global, leading to potential name collisions and unintended side effects.
- How can
strict mode
affect variable declarations in JavaScript?- In strict mode, undeclared variables cannot be used, and using them will throw a ReferenceError.
What is “undefined” property?
The undefined property indicates that a variable has not been assigned a value, or declared but not initialized at all. You can clear out any variable by assigning the value undefined
to it.
var myName;
console.log(myName); //undefined
console.log(typeof myName); //undefined
What is null value?
In JavaScript, null
is a special value that represents the absence of any value or an empty value. It is often used to explicitly indicate that a variable does not currently have a meaningful value.
let x = null; // Assigning null to a variable
console.log(x); // Outputs: null
let y; // Variable declared but not assigned a value
console.log(y); // Outputs: undefined
console.log(null == undefined); // Outputs: true
console.log(null === undefined); // Outputs: false
What is difference between null and undefined
Feature | null | undefined |
---|---|---|
Type | object | undefined |
Meaning | Represents the intentional absence of any object value. | Represents the default value for uninitialized variables. |
Usage | Often assigned by developers to indicate no value. | Automatically assigned by JavaScript engine to uninitialized variables. You can clear out any variable by assigning the value undefined to it. |
Equality | null == undefined Output: true | undefined == null Output: true |
Primitive operations | Converted to zero (0) while performing primitive operationslet x = null; let result = x + 5; console.log(result); // Outputs: 5 In this example, null is converted to 0 when used in an arithmetic operation (+ ). Therefore, result equals 0 + 5 , resulting in 5 . | Converted to NaN while performing primitive operations.let y; In this example, undefined is converted to NaN when used in an arithmetic operation (+ ). Therefore, result becomes NaN because NaN + 10 results in NaN . |