Global Scope II: console.log order - sky.js


#1

link https://www.codecademy.com/courses/learn-javascript-scope/lessons/scope/exercises/global-scope-ii?action=lesson_resume&course_redirect=introduction-to-javascript

If we write the code like this:

const satellite = 'The Moon';
const galaxy = 'The Milky Way';
let stars = 'North Star';

const myNightSky = () => {
  stars = 'Sirius';
  return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
};

console.log(myNightSky());
console.log(stars);

the result is: // Night Sky: The Moon, Sirius, The Milky Way // Sirius

But if we chande de console.log order, writing code like this:

const satellite = 'The Moon';
const galaxy = 'The Milky Way';
let stars = 'North Star';

const myNightSky = () => {
  stars = 'Sirius';
  return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
};

console.log(stars);
console.log(myNightSky());

the result is: //“North Star” // “Night Sky: The Moon, Sirius, The Milky Way”.

Can anyone explain me why?


#2

If the function call is first, starts variable gets updated to sirius by the function

if stars is logged to console before you call the function, starts won’t yet be updated/re-assigned, causing different output


#3

I thought that the code was ready as we (human) read a book and not only when it’s logged or call…Thank you!


#4

for the most part this is actually true, with a few exceptions

the function is interpreted (or compiled, depending on the language) first, but its sort of like a task or todo list. We can write such a list (aka function), but we haven’t actually done it. We can do it later. Its the same with functions


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.