Using Whitespace
Whitespace is any character that is typed using your keyboard but not visible in your source code, like space, tab, or enter(new line). Because doesn't matter what language, there always seems to be blank line and indentation. Check this code written in Java, you can see what I talking about.
class RandomDemo{
public static void main(String args[]){
for(int i=1;i<=5;i++){
System.out.println((int)(Math.random()*100));
}
}
}
So the question is, is whitespace even matter in our source code? And by that, I mean if we change our source with, for example, adding more whitespace for specific instruction, will that code behave differently from before? Are those java code work different now if I changed it?
class RandomDemo{
public static void main(String args[]){
for(int i=1;i<=5;i++){
System.out.println((int)(Math.random()*100));
}
}
}
More programming language don't care very much about whitespace. Look at example below :
Add 99 to current score
If you change that statement like this :
Add 99 to current score
You still can read that code and know what they do, so it not really matters. But if you type like this :
Add 99 to curr
entscore
You see, now it's confusing. The language must be able to recognize each element of the statement. Beyond that, in most language, it doesn't matter if you have more than one space between the element of your statement or you add extra blank line betwen them. They just ignore it.
Whitespace for Programmer
Whitespace is still important, but it's more for us, the programmer. Computer might not care, but for programmer, we use whitespace to make our program more readable. Programmer often work with their program months, even years, to fix bug, add new feature, and sometimes change code that other people wrote. We want our source code readable and understandable so easier to us do our job.
Whitespace for Some Language
There are few situations where whitespace can be more significant than just for easy reading. In Python for example, having whitespace at the start of the line is matters. In Python, indentation is used to tell computer that some certain line of code belog together.
if playerScore > highScore
print("Congratulation, you have the high score!")
highScore = playerScore
print("Thank you for playing")
In code above, computer will print "Thank you for playing" even when playerScore is lower than highScore. Now if we change the code to be :
if playerScore > highScore
print("Congratulation, you have the high score!")
highScore = playerScore
print("Thank you for playing")
Computer now will print "Thank you for playing" only if playerScore is higher than highScore. Different whitespace make program work differently.
Many other language, like Swift or Java, use opening and closing curly braces to group lines of code, so whitespace doesn't really matters anymore.