Understanding Javascript Pass by Value

Scenario

We have a javascript variable greeting and a function that changes the greeting mutateGreeting and we are wondering what happens to the greeting variable when we change it inside the function.

let greeting = "Hei!"
function mutateGreeting(greeting) {
return greeting = "Hola!"
}

Answer

Nothing.

Javascript is

Pass by Value

When we pass greeting into the function a copy of it is created and we are changing the copy.

Demo

Brought to You By

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation