Variables - JavaScript Interview Questions
JavaScript Fundamentals: JavaScript Variables
What is the definition of a variable in JavaScript?
View Answer:
What are the keywords used to declare a variable in JavaScript?
View Answer:
Can you declare multiple variables on one line?
View Answer:
// Example: one-line
let user = 'John',
age = 25,
message = 'Hello';
// The multiline variant is a bit longer, but easier to read:
let user = 'John';
let age = 25;
let message = 'Hello';
Is there a way to copy stored data from one variable to another?
View Answer:
let hello = 'Hello JavaScript!';
let message;
// copy 'Hello world' from hello into the message
message = hello;
// now two variables hold the same data
console.log(hello); // Hello world!
console.log(message); // Hello world!
Does JavaScript allow you to change the value of a variable?
View Answer:
let message;
message = 'Hello!';
message = 'World!'; // value changed
console.log(message); // returns 'World!'
Can you declare a variable twice in JavaScript?
View Answer:
'use strict';
let message = 'This';
// repeated 'let' leads to an error
let message = 'That'; // SyntaxError: 'message' has already been declared
What are the limitations of variable names in JavaScript?
View Answer:
let userName;
let test123;
let $ = 1; // declared a variable with the name "$"
let _ = 2; // and now a variable with the name "_"
console.log($ + _); // 3
// Invalid variable names
let 2ndName = "Alex"; // Cannot start with a number
let full-name = "John Doe"; // Cannot use hyphen
let for = "loop"; // Cannot use reserved keyword
What is Lower CamelCase in JavaScript?
View Answer:
let firstName = "John";
let lastName = "Doe";
let age = 30;
let favoriteColor = "blue";
In this example, the variable names use Lower Camel Case, with the first word in lowercase and the first letter of each subsequent word capitalized. This naming convention is commonly used in JavaScript for variable names, function parameters, and object properties.
Lower Camel Case is a popular naming convention because it is easy to read and understand, and it is consistent with the style used in many programming languages. It is important to choose a consistent naming convention throughout your codebase to improve readability and maintainability.
Can you explain the CamelCase naming method?
View Answer:
// variable in CamelCase
let myFavoriteColor = "blue";
console.log(myFavoriteColor); // returns 'blue'
CamelCase is a popular naming convention in JavaScript and is often used for variable names, function names, and object properties. It helps to make the code more readable and easier to understand.
It is important to note that while CamelCase is widely used in JavaScript, there are other naming conventions such as snake_case, kebab-case, and PascalCase. The choice of naming convention often depends on personal preference, team conventions, and the specific use case. However, using a consistent naming convention throughout your codebase can improve readability and maintainability.
In JavaScript, What stylization rule gets used in naming multi-word variables?
View Answer:
let myUserName;
What is the stylization rule used for naming multi-word constructors in JavaScript?
View Answer:
function CarModel(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var myCar = new CarModel("Honda", "Civic", 2022);
In this example using the PascalCase naming convention to define a constructor function for a car model with three parameters: make, model, and year. We then create a new instance of this object using the new keyword and passing in some values for each of the parameters. The resulting object, myCar, has properties for make, model, and year based on the values we passed in.
Does variable case matter in JavaScript?
View Answer:
var myVariable = "hello";
var myvariable = "javascript";
console.log(myVariable); // Output: "hello"
console.log(myvariable); // Output: "javascript
In this example, we have defined two variables with different casing - myVariable and myvariable. If we try to log the values of these variables to the console, we'll see that they are indeed different variables with different values.
It's important to note that while variable case does matter in JavaScript, it's generally considered good practice to use consistent naming conventions to make your code more readable and easier to understand. For example, you might choose to use camelCase for variable names, where the first word is in lowercase and subsequent words start with a capital letter. This convention is widely used in JavaScript and can make your code more consistent and easier to read, especially if you're working with other developers who are also following this convention.
In JavaScript, Are Non-Latin letters allowed in naming variables?
View Answer:
var π = 3.14;
var こんにちは = "Hello";
console.log(π); // Output: 3.14
console.log(こんにちは); // Output: "Hello"
// More Examples
let имя = '...';
let 我 = '...';
In this example, we've defined two variables using non-Latin characters. The first variable uses the Greek letter pi (π) as its name, and the second variable uses the Japanese greeting "こんにちは" (pronounced "Konnichiwa"). When we log the values of these variables to the console, we can see that they work just like any other variables in JavaScript.
It's important to note, however, that while you can use Unicode characters in variable names, it's generally considered good practice to stick to more conventional naming conventions that are easy to read and understand for other developers who may be working with your code.
Is it possible to declare a variable without let, const, or "The Old var"?
View Answer:
myVariable = "Hello, JavaScript!";
console.log(myVariable); // output: Hello, JavaScript
"use strict";
myVariable = "Hello, JavaScript!";
console.log(myVariable); // error thrown
In this example, we simply assign a value to a variable called myVariable without using any of the usual variable declaration keywords. This will work in most cases, but it's important to note that doing so creates an implicit global variable, which can lead to unintended consequences if the variable is accidentally overwritten or used in other parts of the code.
It's generally considered best practice to always use let, or const to declare variables explicitly and avoid creating global variables unintentionally.
What is the difference between var and let in JavaScript?
View Answer:
function test() {
var x = 1;
let y = 2;
if (true) {
var x = 3;
let y = 4;
console.log(x); // Output: 3
console.log(y); // Output: 4
}
console.log(x); // Output: 3
console.log(y); // Output: 2
}
test();
In this example, we've declared two variables, x and y, using var and let, respectively. We've also used an if statement to create a block scope. When we log the values of x and y within the block, we can see that they have different values due to the block scope of let. However, when we log the values of x and y outside of the block, we can see that the var declaration of x has overwritten the original value of x within the function.
It's generally considered best practice to use let instead of var for declaring variables in modern JavaScript, as it helps to avoid unintended variable reassignment and makes it easier to reason about the scope of variables within your code.
Can you reassign a value in a variable declared with const?
View Answer:
const myConst = "Hello";
myConst = "JavaScript!"; // error, can't reassign the constant!
In this example, we've declared a variable called myConst with the value "Hello". When we try to reassign a new value to myConst to “JavaScript” using the assignment operator (=), we get an error indicating that we cannot assign a new value to a constant variable.
const is used to declare variables whose values should not change over time. This can help prevent unintended changes to variables and make code more predictable and easier to reason about. If you need to declare a variable whose value may change over time, you should use let instead.
When should you use a constant as an alias in JavaScript?
View Answer:
const COLOR_RED = '#F00';
const COLOR_GREEN = '#0F0';
const COLOR_BLUE = '#00F';
const COLOR_ORANGE = '#FF7F00';
// ...when we need to pick a color
let color = COLOR_ORANGE;
console.log(color); // #FF7F00
What are the advantages of aliasing a constant in JavaScript?
View Answer:
In JavaScript, When should a constant be named in all caps?
View Answer:
What are some excellent rules for variable naming conventions?
View Answer:
Some good-to-follow rules are:
- Use names that are easy to remember, such as userName or shoppingCart.
- If you do not know what you are doing, avoid abbreviations or short names like a, b, and c (Ninja Coder – is not a great approach to creating code).
- Make your names as descriptive and straightforward as possible. Two instances of bad names are data and value, and such names are nonsensical, and they may only be used in a coding context to make it apparent what data or value the variable refers to in our code.
- Make terms with your team. When a site visitor gets referred to as "user," related variables, currentUser or newUser are utilized rather than currentVisitor or newLadyInRed.
- A variable name is always camelCase and should begin with a noun to differentiate variables from functions, which generally should begin with a verb.
What differentiates variable and function naming conventions?
View Answer:
What is the difference between a global and local variable?
View Answer:
What is the scope of a variable in JavaScript?
View Answer:
What is variable shadowing in JavaScript?
View Answer:
let x = 10;
function foo() {
let x = 20; // local variable shadows the outer variable
console.log(x); // prints 20
}
foo();
console.log(x); // prints 10
In the above example, the variable x is defined in the global scope with a value of 10. Inside the foo function, a local variable with the same name is declared and assigned the value of 20. This variable shadowing causes the outer x variable to be temporarily hidden and inaccessible within the foo function. When the console.log statement is called inside foo, it prints the value of the local x variable, which is 20. However, when the console.log statement is called outside the foo function, it prints the value of the outer x variable, which is 10. This is because the local x variable has a different scope and does not affect the value of the outer x variable.
What is the difference between null and undefined in JavaScript?
View Answer:
let x; // undefined variable
let y = null; // variable explicitly assigned null value
console.log(x); // prints undefined
console.log(y); // prints null
In the above example, x is declared but not assigned a value, so it has the value of undefined. On the other hand, y is explicitly assigned the value of null. When console.log is called on x, it prints undefined. When console.log is called on y, it prints null. It's important to note that undefined is also returned by a function when a return statement is not provided or when accessing an object property that doesn't exist.