• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Scope in Javascript with example

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
JavaScript is a powerful and versatile programming language that is widely used for web development. One of the key concepts in JavaScript is scope, which refers to the accessibility of variables, functions, and objects within a program. In this blog post, we will explain the different types of scope in JavaScript, including global scope, local scope, and function scope, and provide examples to help you understand how they work.

Global scope

Global scope in JavaScript refers to variables, functions, and objects that can be accessed from anywhere within a program. These variables, functions, and objects are defined outside of any function or block of code.
For example, consider the following code:


let globalVariable = "Hello, World!";

function myFunction() {
console.log(globalVariable); // prints "Hello, World!"
}

console.log(globalVariable); // prints "Hello, World!"

In this example, the variable globalVariable is declared outside of any function or block of code, making it accessible from anywhere within the program. Both the myFunction function and the console.log statement outside of the function are able to access and print the value of globalVariable.

Local scope
Local scope in JavaScript refers to variables, functions, and objects that can only be accessed within a specific block of code. These variables, functions, and objects are defined within a block of code, such as a if statement or a for loop.
For example, consider the following code:


if (true) {
let localVariable = "Hello, World!";
console.log(localVariable); // prints "Hello, World!"
}

console.log(localVariable); // throws an error, localVariable is not defined

In this example, the variable localVariable is defined within the if statement, making it only accessible within that block of code. The console.log statement within the if statement is able to access and print the value of localVariable, but the console.log statement outside of the if statement throws an error because localVariable is not defined in the global scope.

In conclusion, understanding the concept of scope in JavaScript is essential for writing clean, efficient, and maintainable code. JavaScript has three main types of scope: global scope, function scope, and block scope (commonly referred to as local scope).


  • Global scope applies to variables and functions that are declared outside of any function or block, making them accessible throughout the entire program.


  • Function scope means variables declared within a function are only accessible inside that function.


  • Block scope, introduced with let and const in ES6, restricts variable access to the block (e.g., within {}) in which they are defined.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу