综合技术

Scope of variables in JavaScript

微信扫一扫,分享到朋友圈

Scope of variables in JavaScript
0

What is thescope of variables in Javascript?

Scope in javascript refers to the variables and the functions which are accessible and in what context it will be executed. There are basically 2 types of scope which I would discuss in this article.

Global Scope Variables

Global variables are usually declared at the top level and it will be accessible anywhere in the code.

var category = "Javascript Blog"; // global scope variable. All the methods will be able to access this variable.
 
function ReadBlogLine() {
 return alert(category);
}

Local Scope Variables

Local variables in Javascript are limited to certain part of the code or method. Hence, only the method will be able to access the variables.

function ReadBlogLine() {
var myLocalVariable="Hello World";
 return alert(myLocalVariable);
}
alert(myLocalVariable);// Throws an error because the scope is local to the method here.

Let us take a look at javascript scope of variables in nested functions

In the below example you can see the variable name is declared in the animal function and it is also accessible in the animal count function and JoinAnimalNames function. The variable will be accessible easily inside the nested functions. The variable namesLength is a local scope to animalsCount method and this will not be accessible in any other methods.

function animals () {
 var names = ["CAT", "DOG", "RABBIT"];
 function animalsCount () {
 var namesLength= animals.length;
 return namesLength;
 }
 function JoinAnimalNames() {
 return "I have " + animalsCount() + " Pets at home:nn" + names.join("n");
 }
 return JoinAnimalNames(); 
}
alert(animals ()); // I have 3 Pets at home CAT DOG RABBIT

阅读原文...


Echo JS

Kubernetes: The Surprisingly Affordable Platform for Personal Projects

上一篇

TNW Part 13 - Scripted Prototype Card Generation

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Scope of variables in JavaScript

长按储存图像,分享给朋友