It's called scoping and hoisting.There are two types of scope in javascript, they are Global scope and Function scope.In javascript functions create their own scope.
So your code is equivalent to the following :
var skill; // hoisted at the top of global scope and undefined
skill = "JavaScript"; // value assigned to it
function printSkill() {
var skill; //--> Hoisted at the top of function's scope and it is undefined
console.log(skill); // <-- So this prints undefined
skill = "Java"; // <-- here it is assigned a value "java"
console.log(skill); // <-- This prints "Java"
}
printSkill();
Now come to the second skill variable inside printSkill()
. It has it's own scope.It's called function scope.And all the variables which is defined inside this function is hoisted at the top of it's wrapper function's scope ,not on global scope.
So when you console.log() variable skill
inside pritSkill()
first it looks in functions scope.If it doesn't find it there then it will look up in the scope chain.In your case it finds skill hoisted at the top of the function but it is not assigned any value.So first console.log() prints undefined.
In second console.log()
it finds skill assigned a value.So it prints the value which is assigned to skill
In your code, if you want to initialize your global skill
variable, you can not declare any other variable having same name as the global one.Declaration order doesn't count due to hoisting as I've mentioned above.Here is how the code should be written.
Note : declaring global variables here and there in your code is considered bad coding practice
var skill = "JavaScript";
function printSkill() {
console.log(skill); // <-- This prints "javascript"
skill = "Java"; // <-- assign value "Java" to global "skill" variable
console.log(skill); // <-- This prints "Java"
}
printSkill();