Understanding Strict Mode and Variables in JavaScript

You are currently viewing Understanding Strict Mode and Variables in JavaScript

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

  1. What are the different ways to declare a variable in JavaScript?
    • var, let, and const.
  2. 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.
  3. 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 with let and const are also hoisted but are not initialized, leading to a “temporal dead zone.”
  4. What is the scope of a variable declared with var?
    • Function scope.
  5. What is the scope of a variable declared with let and const?
    • Block scope.
  6. 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.
  7. What will happen if you try to reassign a const variable?
    • It will throw a TypeError.
  8. Can you declare a variable without initializing it? What will be its value?
    • Yes, it will be undefined.

Advanced Concepts

  1. 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 or const. During this period, accessing the variable results in a ReferenceError.
  2. How do var, let, and const variables behave inside loops?
    • var variables are function-scoped and can lead to unexpected results inside loops due to hoisting.
    • let and const are block-scoped and thus confined to the loop block, avoiding such issues.
  3. 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, or const keyword (not recommended).
  4. What is the purpose of the global object in JavaScript, and how do variables interact with it?
    • The global object (like window in browsers and global in Node.js) is the top-level object that contains all global variables and functions. Global variables declared with var become properties of this object.
  5. 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.
  6. 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.
  7. 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.
  8. 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

  1. 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.
  2. How do you ensure a variable is not reassignable after its initial assignment?
    • Declare it using const.
  3. 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.
  4. 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.
  5. Why is it generally recommended to use let and const over var?
    • let and const provide block scope, reducing the likelihood of bugs caused by variable hoisting and unintentional overwriting.

Best Practices and Common Pitfalls

  1. 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.
  2. 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.
  3. Can you give an example of a situation where using const is preferable to let?
    • Use const when the variable should not be reassigned, such as when defining configuration settings or fixed values.
  4. 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.
  5. What issues can arise from forgetting to use let or const when declaring a variable?
    • The variable will become global, leading to potential name collisions and unintended side effects.
  6. 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

Featurenullundefined
Typeobjectundefined
MeaningRepresents the intentional absence of any object value.Represents the default value for uninitialized variables.
UsageOften 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.
Equalitynull == undefined
Output: true
undefined == null
Output: true
Primitive operationsConverted to zero (0) while performing primitive operations
let 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;
let result = y + 10;
console.log(result); // Outputs: NaN

In this example, undefined is converted to NaN when used in an arithmetic operation (+). Therefore, result becomes NaN because NaN + 10 results in NaN.
difference between null and undefined
You can share it on

Leave a Reply