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 trialLi Xia
4,671 Pointswhy is typeof needed
Why does the if argument contain "typeof" operator, what is it's role in the statement?
5 Answers
Stone Preston
42,016 PointsIts there for the case when the user doesnt pass in a greeting to the function. using typeof checks if the greeting argument is "undefined" which means it wasnt passed in to the function. So if they do pass in a greeting such as "welcome" to the function, they function will print "welcome" followed by whatever there name is. if they dont pass in a greeting, the function will just set the greeting to hello and use the default value you defined in the if statement
Li Xia
4,671 PointsThanks Preston.
Monkey D Luffy
iOS Development Techdegree Student 4,919 PointsThe if statement still works if you remove typeof. Is it really needed for this example?
Monkey D Luffy
iOS Development Techdegree Student 4,919 Pointsfunction sayHello (name,greeting) { if(greeting===undefined){ greeting="Hi friend"; } console.log(greeting+" Yo momma name is " + name); } sayHello("Jim");
This correctly outputs Hi friend Yo momma name is Jim functions.js:5
Stone Preston
42,016 Pointsyes. thats the expected behavior. you did not pass in a greeting argument. so it set "Hi Friend" as the greeting. if you pass in a greeting argument like so:
sayHello("Jim", "Salutations")
it would output Salutations Yo momma name is Jim
Monkey D Luffy
iOS Development Techdegree Student 4,919 PointsYeah, but I didn't include typeof and it still worked without passing a argument for greeting. That is why I was wondering if typeof is even needed.
Stone Preston
42,016 Pointsah ok i see what you are saying now. sorry, misunderstood your question. Technically the typeof is not required according to this post However the value of undefined can be overwritten, so its best practice to use typeof to check for undefined values. also you will get a reference error if you check for undefined without using typeof if the variable has not been declared yet. So using typeof is safer, and is probably what you should use.