Useful Code

As we wrap up JavaScript, here is some miscellaneous code that you may find helpful down the road.

Randomizer:  random(lowest number, highest number);

The randomizer generates a number between the lowest and highest number you have defined. They can have decimal places, so keep that in mind. This can come in handy when you need to run a program with if or if/else statements. A new number will be generated each time the program is run and therefore will change the outcome of the statements used. The randomizer code would be used as a value for a variable since it won’t do anything on its own.

Round: round(variable);

The round code will round whatever is inside of it to the nearest whole number. This would be a good thing to use with the randomizer for certain projects. You can also nest the two together when defining a variable like this:

var answer = round(random(1,20));

The variable would get a new value that the randomizer generated and then was rounded.

Sound: playSound(getSound(sound);

(I have only seen this in Khan Academy so I don’t know if it works outside their software. )

This allows you to use one of Khan Academy’s stored sounds. I use it in if statements so that it’s not too annoying. The getSound tells the computer which sound you want and the playSound tells it to use the sound. When you use this code, there will be a pop-up window with sound choices. Sound can take your program to the next level but can also drive you crazy if not used correctly.

Image: image(image, x,y, width, height);

The image code works almost exactly like the sound code does. The only difference is that you are picking a stored image instead of a sound. The width and height are optional and every picture ahs a default size.

Leave a Reply

Your email address will not be published. Required fields are marked *