Javascript Variable

A JavaScript variable is a named container used to store data values. Variables allow you to store information that can be referenced and manipulated within your program.

JavaScript variable Syntax


(typeOfVariable) variableName = variableValue

Define a variable:- in the below example, variableName name assigned value John


var name="John";

Using a variable:- Now, You can use variable name in the file.


 console.log(name); //John

Note:- If you did not define the variable type then it will work as like var variable,


name="John";
console.log(name); //John

There are two types of JavaScript variable
1) local variable
2) Global variable

1) Local variable:- A variables declared in a function, become LOCAL variable to the function. Local variables have Function scope: They can only be accessed from within the function.


function user() {
  var name = "John";
  console.log(name);
}
	    
user();
console.log(name);  

Note:- When we call console.log(name) after the function user() call then output will be blank.

2) Global Variables:- A variable declared outside a function, becomes GLOBAL variable. A global variable has global scope: All scripts and functions on a web page can access it.


var name = "John";

function myFunction() {

  console.log(name)  
}


Javascript Variable – Interview Questions

Q 1: What is a variable?

Ans: A container for storing data values.

Q 2: How do you create a variable?

Ans: Using var, let, or const.

Q 3: Can variable values change?

Ans: Yes, except const.

Q 4: Are variables case-sensitive?

Ans: Yes.

Q 5: Can a variable start with a number?

Ans: No.

Javascript Variable – Objective Questions (MCQs)

Q1. Variables are used to ______.






Q2. Which keyword is used to declare a variable?






Q3. Variable names must start with ______.






Q4. Which is a valid variable name?






Q5. JavaScript variables are ______ typed.