Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Global Scope

Variables declared globally (outside of any function) have global scope.

Global variables can be accessed from anywhere in a JavaScript program.

When declared outside a block, variables using varlet, and const behave similarly, as they all have global scope.

They all possess global scope.

var x = 2;       // Global scope
let x = 2;       // Global scope
const x = 2;       // Global scope

JavaScript Variables

In JavaScript, objects and functions are considered types of variables as well.

Scope defines the visibility and accessibility of variables, objects, and functions within different parts of the code.

Automatically Global

If you assign a value to a variable that hasn’t been declared, it will automatically become a GLOBAL variable.

In this example, the carName variable will be declared globally, even if the assignment occurs inside a function.

Example

myFunction();

// code here can use carName

function myFunction() {
  carName = “Volvo”;
}