codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript — Learn & Understand Closures

Brandon Morelli
codeburst
Published in
6 min readJan 16, 2018

Closures Defined.

Scope

function speak(){
let words = 'hi';
console.log(words);
}
speak(); // 'hi'console.log(words); // Uncaught ReferenceError: words is not defined
let words = 'hi';function speak(){
console.log(words);
}
speak(); // 'hi'console.log(words); // 'hi'

Nested Functions

function speak() {
return function logIt() {
let words = 'hi';
console.log(words);
}
}
var sayHello = speak();
sayHello;//  function logIt() {
// let words = 'hi';
// console.log(words);
// }
sayHello();
// 'hi'
function speak() {
let words = 'hi';
return function logIt() {
console.log(words);
}
}
var sayHello = speak();
sayHello//  function logIt() {
// console.log(words);
// }
sayHello();
// 'hi'
function speak() {
let words = 'hi';
return function logIt() {
console.log(words);
}
}

Another Example

function name(n) {
return function(a) {
return `${n} likes ${a}`;
}
}
var j = name('Jacob');
var r = name('Robert');
j;//  function (a) {
// return `${n} likes ${a}`;
// }
r;//  function (a) {
// return `${n} likes ${a}`;
// }
j('cheese');  // 'Jacob likes cheese'
r('grapes'); // 'Robert likes grapes'

Closing Notes:

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (13)

Write a response