Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Functions Pass Information Into Functions Function Declarations vs. Function Expressions

Just a doubt regarding function expression

My code just worked without even the semi-colon at the end of the curly bracket. It is not showing an error. Is it okay to write it like the code I have written below?

const getRandomNumber = function(upper) { const randomNumber = Math.floor(Math.random() * upper ) + 1; return randomNumber; } console.log(getRandomNumber(10));

i tried to answer your question and deleted it as soon as I realized I didn't understand it myself.

https://stackoverflow.com/questions/1834642/why-should-i-use-a-semicolon-after-every-function-in-javascript

That link may help.

1 Answer

J A
seal-mask
.a{fill-rule:evenodd;}techdegree
J A
Full Stack JavaScript Techdegree Student 4,646 Points

JavaScript is a little tricky in that you don't always need a semicolon at the end of a line, but it is best practice to put one there, especially if you intend to have multiple statements on one line. In your example you have a function expression and you should use a semicolon at the end, or else there might be some unintended consequences and very subtle bugs.

Casey provided a good StackOverflow link, although the discussion there is a little advanced for a novice programmer. My advice is to always use a semicolon when you create a function expression like you have in your example to avoid potential bugs in your code that are not obvious at the moment.

Side note: remember to use Markdown to format your code for easier reading (click the Markdown Cheatsheet link below the text box). You'll want to use three back-ticks to format a code block like so:

function myFunc = function(param1) {
    alert(`Thanks for giving me ${param1}`);
};

myFunc(123);