In Python if, while and for don't require parentheses, have colons, and use indentation to define the body. In JavaScript, these statements do require parentheses, don't have a colon, and require curly braces to define the body. If you don't write curly braces, the next statement will be considered the body.
| Python | JavaScript |
|---|---|
| True False | true false |
| and | && |
| or | || |
| not | ! |
| None | null |
| self | this |
| if c: | if (c) {} |
| elif c: | else if (c) {} |
| else: | else {} |
| while c: | while (c) {} |
| for i in range(len(mylist)): | for (let i=0; i<myarray.length; ++i) {} |
| a if c else b | c? a: b |
temperature = int(input('what is the temperature?'))
if temperature >= 80:
print('hot')
elif temperature >= 70:
print('warm')
elif temperature >= 60:
print('chilly')
else:
print('cold') let temperature = prompt('what is the temperature?')
if (temperature >= 80) {
alert('hot')
} else if (temperature >= 70) {
alert('warm')
} else if (temperature >= 60) {
alert('chilly')
} else {
alert('cold')
}In Python, while loops don't need parentheses and use a colon and indentation.
i = 0
while i < 10:
print(i)
i += 1In JavaScript while loops need parentheses and use curly braces.
let i = 0
while (i < 10) {
console.log(i)
i += 1
}In Python, for loops are structured very differently:
for i in range(10):
print(i)The three parts of a JavaScript for loop are the initialization, condition, and increment.
for (let i=0; i<10; ++i) {
console.log(i);
}Modulus works differently in each language for negative numbers.
for i in range(-4, 5):
print(f'{i}%3={i%3}')-4%3=2
-3%3=0
-2%3=1
-1%3=2
0%3=0
1%3=1
2%3=2
3%3=0
4%3=1
for (let i=-4; i<5; ++i) {
console.log(i+'%3='+(i%3));
}-4%3=-1
-3%3=0
-2%3=-2
-1%3=-1
0%3=0
1%3=1
2%3=2
3%3=0
4%3=1