×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

Understanding Functions and Scopes in JavaScript

Here, we are going to learn about functions and scopes in JavaScript along with var vs. let keywords and king territory problem.
Submitted by Himanshu Bhatt, on September 15, 2018

Before we dive into variable Scope discussion, let me explain what a function is in JavaScript?

JavaScript functions

Basically, subprograms for a particular task is a function and calling of these functions is known as invoking. It's convenient to have functions and it's a good programming practice. They usually have a return value.

Declare a function

To declare a function we need a name, function keyword, and it may or may not have parameter(s).

Syntax

We can declare function with these ways:

Type A)

function functionName (param1, param2, param3, ...) {
  //function body 
}

Type B)

let funtionNameTwo = function (param1, param2, param3, ...) {
  //function body 
}

Type C)

var funtionNameThree = function (param1, param2, param3, ...) {
    //function body 
}

As here we have three ways to declare a function, my personal favorite is type B, so I will use it in this article, you can use whatever you like.

Function return type (return value)

It's a value that a function returns value to the system on completion.

Example

Let's try some examples...

let tempConversion = function(celsius){
    fahrenheit = (celsius * 9/5) + 32   
    return fahrenheit 
}

todayTemp = tempConversion(45)
yesterdayTemp = tempConversion(38)
tomorrowTemp = tempConversion(40)

console.log(`Temp for 3 consecutive days are ${yesterdayTemp}F, ${todayTemp}F, ${tomorrowTemp}F`)

Note:

If you noticed in the above code I used ' ' (you can find this symbol at the left of your number 1 key above tab button) symbol instead of inverted commas (" ") because we can use any variable's value in ${variableName} manner.

If you notice at some places I declared a variable with var keyword while some with let keyword, so why using different keywords for declaring a variable?

Let's see the code snippet that I run for you...

js program

In the above sample, we have both var and let keywords used, one inside a function and another outside side of it, let's check its output.

js program output

OOPS!!!! It's some kind of error, now we have to see what it is. There is an output that is produced from the invoking of exampleFunction() so log function outside of our function.

In the first highlighted box, it looks like we got something as output, it says.

Value of x: x-inside Value of y: y-outside.

In the second highlighted section, there is an error which says ReferenceError: x is not defined. Wait a minute we declared x, so happened to it?

Well, the answer is simple when we use let keyword the variable is a local variable and if we use var keyword then the variable is the global scope.

Well, this is something new that I haven't told you about, so let discuss.

Scope in JavaScript

Scope simply refers to where a variable or a function is accessible.

Types of Scopes in JavaScript

  1. Global Scope: When a variable or a function is global then it can be accessed anywhere in our code.
  2. Local Scope: When an anything can only be accessed inside a block or a function.

Variable also have a function scope that is those which are passed as an argument in function parameter and the variable can be accessed within the function.

Let's understand scopes better with a problem. The problem is the KINGS territory problem.

KINGS territory problem

let king = 'foo'    // line 1

if(true) {
	let king = 'bar'    //line 2
	if(true){
		let king = 'IncludeHelp'    //line 3
		console.log(king)
	}
}

if(true){           //block 1
	console.log("King at out side is:",king);
}

In the above code, we declared king in line 1 with let keyword and it will act as a global variable as it is declared in global domain hence in subsequent blocks it will be accessible.

Here is the task for you, in the above code try some variation like commenting line 1, 2, 3, 4 or block 1 and run it and see what happens.

JavaScript Tutorial »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.