Python.v.JavaScript

JavaScript for Pythonistas. Python for JavaScripters

Scopes

Variable names (including function names) in Python and JavaScript can belong to different scopes. For example, local variable defined inside function is not accessible from outside of a function.

Python Javascript
Default variable scope #
x = 1
def fun():
    x = 2
    print("Inside function, x =", x)
fun()
print("Outside function, x =", x)
Inside function, x = 2
Outside function, x = 1

By default, variable declared inside a function is a local one.


x = 1
def fun():
    global x
    x = 2
    print("Inside function, x =", x)
fun()
print("Outside function, x =", x)
Inside function, x = 2
Outside function, x = 2

To be able to modify the global variable inside a function one have to use global command.

x = 1;
function fun() {
    x = 2;
    console.log("Inside function, x =", x)
}
fun();
console.log("Outside function, x =", x)
Inside function, x = 2
Outside function, x = 2

If one creates variable inside a function in JavaScript, by default it is a global variable. To declare a local variable, one have to use command var.


x = 1; // global x
function fun() {
    var x = 2; // local x
    console.log("Inside function, x =", x)
}
fun();
console.log("Outside function, x =", x)
Inside function, x = 2
Outside function, x = 1

function sum_of_numbers(k) {
    var s=0;
    for (i=0; i<k; i++) {
        s += i
    }
    return s
}
i = 5;
console.log("Sum of numbers from 1 to 100 is", 
            sum_of_numbers(101));
console.log("And i =", i);
Sum of numbers from 1 to 100 is 5050
And i = 101

We forgot to declare variable i — and here is the result.

© Ilya V. Schurov and contributors, 2017
Licenses: CC BY (text), MIT (code).
contribute on github