'Functions and Strings in JavaScript
I'm just starting programming, I have this issue and I can't finish it. where to use startsWith
inside the function?
function werewolfCheck(name) {
if (name === str.startsWith('were')) {
return 'It is a werewolf';
} else {
return 'Just a regular person';
}
}
var werewolfCheck = name.str.startsWith('were');
werewolfCheck('werebrian');
Solution 1:[1]
in the function
str
doesn't exist so you just need to check to see ifname
(the argument you passed in) starts with 'were'.var werewolfCheck...
does nothing useful so you can remove it.The return from the function is a string so you need some way to display that string. I've logged it to the console in this example.
function werewolfCheck(name) {
if (name.startsWith('were')) {
return 'It is a werewolf';
} else {
return 'Just a regular person';
}
}
console.log(werewolfCheck('werebrian'));
console.log(werewolfCheck('Billy Joel'));
Solution 2:[2]
function werewolfCheck(name){
if(name.startsWith("were"))
return "It is werewolf";
return "Just a regular person";
}
werewolfCheck("werebrain");
Solution 3:[3]
You can use ternary operator and ES6 arrow function as cleaner and more readable solution
const werewolfCheck = (name) => {
return name.startsWith('were') ? 'It is a werewolf' :'Just a regular person';
}
console.log(werewolfCheck('werebrian'));
console.log(werewolfCheck('Billy Joel'));
Solution 4:[4]
function werewolfCheck (name) {
if (name.slice(0,4) === "were"){
return "it is a werewolf"
} else {
return "just a regular person"
}
};
console.log(werewolfCheck("werebrian"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andy |
Solution 2 | SaminatorM |
Solution 3 | |
Solution 4 | YehosuaEs |